package com.ybkj.o2o.zhuanche.manager.impl;

import com.alibaba.fastjson.JSON;
import com.ybkj.o2o.zhuanche.common.api.DaijiaApi;
import com.ybkj.o2o.zhuanche.common.api.PassengerApi;
import com.ybkj.o2o.zhuanche.controller.v4.ErrorConstantV4;
import com.ybkj.o2o.zhuanche.controller.v4.ResultTransport;
import com.ybkj.o2o.zhuanche.entity.OrderGroup;
import com.ybkj.o2o.zhuanche.entity.OrderTemp;
import com.ybkj.o2o.zhuanche.entity.Passenger;
import com.ybkj.o2o.zhuanche.entity.ServiceEntity;
import com.ybkj.o2o.zhuanche.entity.ServiceType;
import com.ybkj.o2o.zhuanche.manager.OrderTempManager;
import com.ybkj.o2o.zhuanche.service.OrderGroupService;
import com.ybkj.o2o.zhuanche.service.OrderTempService;
import com.ybkj.o2o.zhuanche.service.ServiceTypeService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DefaultOrderTempManager implements OrderTempManager {
  @Autowired
  private OrderTempService orderTempService;

  @Autowired
  private ServiceTypeService serviceTypeService;

  @Autowired
  private OrderGroupService orderGroupService;

  @Autowired
  private DaijiaApi daijiaApi;

  @Autowired
  private PassengerApi passengerApi;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public OrderTemp insert(Long companyId, String companyName, Long passengerId,
      String passengerName, String passengerPhone, String showPhone, Long carTypeId,
      String channelName, String startAddress, String startAddressDetail, Double startLat,
      Double startLng, String endAddress, String endAddressDetail, Double endLat, Double endLng,
      Date serverDate, Double prestartPrice, Double premileagePrice, Double prerunTimePrice,
      Double budgetPay, Double shouldPay, Long couponId, Integer pretravelTime, Double premileage,
      String createOrderName, String appKey) {
    OrderTemp orderTemp = new OrderTemp();
    orderTemp.setCompanyId(companyId);
    orderTemp.setCompanyName(companyName);
    orderTemp.setPassengerId(passengerId);
    orderTemp.setPassengerName(passengerName);
    orderTemp.setPassengerPhone(passengerPhone);
    orderTemp.setShowPhone(showPhone);
    orderTemp.setCarTypeId(carTypeId);
    orderTemp.setChannelName(channelName);
    orderTemp.setStartAddress(startAddress);
    orderTemp.setStartAddressDetail(startAddressDetail);
    orderTemp.setStartLat(startLat);
    orderTemp.setStartLng(startLng);
    orderTemp.setEndAddress(endAddress);
    orderTemp.setEndAddressDetail(endAddressDetail);
    orderTemp.setEndLat(endLat);
    orderTemp.setEndLng(endLng);
    orderTemp.setServerTime(serverDate);
    orderTemp.setPrestartPrice(prestartPrice);
    orderTemp.setPremileagePrice(premileagePrice);
    orderTemp.setPrerunTimePrice(prerunTimePrice);
    orderTemp.setBudgetPay(budgetPay); // 预算总金额
    orderTemp.setRealPay(shouldPay); // 预算总金额在抵消优惠券后的应付金额
    orderTemp.setCouponId(couponId); // 优惠券Id
    orderTemp.setPretravelTime(pretravelTime);
    orderTemp.setPremileage(premileage);
    orderTemp.setTreatment(false);
    orderTemp.setCreateOrderName(createOrderName);
    orderTemp.setAppkey(appKey);
    int insert = orderTempService.insert(orderTemp);
    if (insert != 1) {
      throw new RuntimeException("临时下单失败!!");
    }
    return orderTemp;
  }

  @Override
  public OrderTemp findByIdAndAppKey(Long orderId, String appKey) {
    return orderTempService.findByIdAndAppKey(orderId, appKey);
  }

  @Override
  public void update(Long orderId, String appKey) {
    OrderTemp temp = orderTempService.findByIdAndAppKey(orderId, appKey);
    temp.setTreatment(true);
    orderTempService.update(temp);
  }

  @Override
  public ResultTransport createV4up(Long passengerId, String passengerName, String passengerPhone,
                                    String userPhone, Long companyId, String companyName, String channelName, Date serverDate,
                                    String startAddress, Double startLat, Double startLng, String endAddress, Double endLat,
                                    Double endLng, Boolean prePay, Integer travelTime, Double mileage, String memo,
                                    String flightNo, String trainNo, String operator, Long serviceTypeId, String serviceType,
                                    String carTypes, String serverUrl, Double couponMoney,
                                    String createOrderName, String appKey, Integer bookStatus,Integer isMakePrice,BigDecimal makePrice) {
    List<OrderTemp> orderList = new ArrayList<OrderTemp>();
    List<ServiceEntity> list = new ArrayList<ServiceEntity>();
    list = JSON.parseArray(carTypes, ServiceEntity.class);

    Integer orderNumber = 0;
    Double orderPayMoney = 0.0;
    for (ServiceEntity serviceEntity : list) { // 遍历车辆类型
      orderNumber += serviceEntity.getNumber(); // 车型用车数量
      orderPayMoney = orderPayMoney + (serviceEntity.getNumber() * serviceEntity.getBudgetPay());
    }

    OrderGroup orderGroup = new OrderGroup();
    if (orderNumber > 1) {
      orderGroup.setPrepay(prePay);
      orderGroup.setPayMoney(orderPayMoney);
      orderGroup.setAppKey(appKey);
      orderGroupService.insert(orderGroup);
    }

    for (ServiceEntity serviceEntity : list) { // 遍历车辆类型
      Integer number = serviceEntity.getNumber(); // 服务类型用车数量
      String couponIds = serviceEntity.getCouponIds();
      List<String> couponIdList = new ArrayList<String>(); // 多张优惠券id
      if (StringUtils.isNotBlank(couponIds)) {
        String[] split = couponIds.split(",");
        Collections.addAll(couponIdList, split);
      }
      List<String> employIdList = new ArrayList<String>();// 该车型的收藏司机id
      String employIds = serviceEntity.getEmployIds();
      if (StringUtils.isNotBlank(employIds)) {
        String[] split = employIds.split(",");
        Collections.addAll(employIdList, split);
      }
      Long carTypeId = serviceEntity.getCarTypeId();
      Double budgetPay = serviceEntity.getBudgetPay();
      Double moneyCoupon = serviceEntity.getCouponMoney();
      Double startPrice = serviceEntity.getStartPrice();
      Double mileagePrice = serviceEntity.getMileagePrice();
      Double travelTimePrice = serviceEntity.getTravelTimePrice();
      Long areaId = serviceEntity.getAreaId();
      ServiceType type = new ServiceType();
      for (int i = 0; i < number; i++) {
        OrderTemp order = new OrderTemp();
        order.setPassengerId(passengerId);
        order.setPassengerName(passengerName);
        order.setPassengerPhone(passengerPhone);
        order.setShowPhone(userPhone);
        order.setCompanyId(companyId);
        order.setCompanyName(companyName);
        order.setChannelName(channelName);
        order.setServerTime(serverDate);
        order.setStartAddress(startAddress);
        order.setStartLat(startLat);
        order.setStartLng(startLng);
        order.setEndAddress(endAddress);
        order.setEndLat(endLat);
        order.setEndLng(endLng);
        order.setBudgetPay(budgetPay);
        order.setCouponMoney(moneyCoupon);
        order.setPrestartPrice(startPrice);
        order.setPremileagePrice(mileagePrice);
        order.setPrerunTimePrice(travelTimePrice);
        order.setPretravelTime(travelTime);
        order.setPremileage(mileage);
        order.setBookStatus(bookStatus);
        order.setMakePrice(makePrice);
        order.setIsMakePrice(isMakePrice);
        if (serviceTypeId != null) {
          type = serviceTypeService.findByServiceTypeId(serviceTypeId, appKey);
        } else {
          type = serviceTypeService.findByNameAndCarTypeId(
              carTypeId, companyId, serviceType, appKey);
        }
        order.setCarTypeId(carTypeId);
        order.setServiceTypeId(type.getId());
        order.setAreaId(areaId);
        order.setCreateOrderName(createOrderName);
        com.ybkj.o2o.zhuanche.entity.Order.ServiceType type2 =
            Enum.valueOf(com.ybkj.o2o.zhuanche.entity.Order.ServiceType.class, type.getName());
        order.setServiceType(type2);
        if (StringUtils.isNotBlank(memo)) {
          order.setMemo(memo);
        }
        if (StringUtils.isNotBlank(flightNo)) {
          order.setFlightNo(flightNo);
        }
        if (StringUtils.isNotBlank(trainNo)) {
          order.setTrainNo(trainNo);
        }
        order.setServerUrl(serverUrl);
        order.setAppkey(appKey);
        if (couponIdList.size() > 0) {
          Long couponId = Long.valueOf(couponIdList.get(0));
          if (!couponId.equals(0L)) {
            order.setCouponId(couponId);
          }
          couponIdList.remove(0);
        }
        if (employIdList.size() > 0) {
          String employId = employIdList.get(0);
          order.setEmployId(Long.valueOf(employId));
          employIdList.remove(0);
        }
        order.setGroupId(orderGroup.getId());
        orderTempService.insert(order);

        orderList.add(order);
      }
    }
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("prePay", prePay);
    if (couponMoney != null) {
      map.put("budgetPay", orderPayMoney - couponMoney);// 预算总金额-优惠的总金额
    } else {
      map.put("budgetPay", orderPayMoney);
    }
    if (null != orderGroup.getId()) { // 一组订单
      map.put("orderGroupId", orderGroup.getId());
      map.put("groupType", "group");
    } else { // 一个订单
      map.put("orderGroupId", orderList.get(0).getId());
      map.put("groupType", "order");
    }
    Map<String, Object> map2 = daijiaApi.queryPaySetting(serverUrl);
    Boolean weixinPay = (Boolean) map2.get("weixinPay");
    Boolean aliPay = (Boolean) map2.get("aliPay");
    Boolean unionPay = (Boolean) map2.get("unionPay");
    map.put("weixinPay", weixinPay);
    map.put("aliPay", aliPay);
    map.put("unionPay", unionPay);
    Passenger passenger = passengerApi.findById(passengerId, appKey);
    if (null != passenger) {
      map.put("overdraw", passenger.getAllowOverdraw());
    } else {
      map.put("overdraw", false);
    }
    ResultTransport transport = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
    transport.setData(map);
    return transport;
  }

  @Override
  public List<OrderTemp> queryByGroupId(Long groupId, String appKey) {
    return orderTempService.queryByGroupId(groupId, appKey);
  }

@Override
public List<Map<String, Object>> countBookTempDriver(Long zhuanYuyueMax,
		Date zhuanYuyueTime, String appKey) { 
	return orderTempService.countBookTempDriver(zhuanYuyueMax, zhuanYuyueTime, appKey);
}

}
